import React from "react";
import {Button, Card, Col, Form, Input, message, Modal, Popconfirm, Result, Row, Spin, Table, Tooltip} from "antd";
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import witty from "@/utils/wittyUtils";
import {connect} from "dva";
import FilterForm from "@/components/BaseForm/FilterForm";
import router from "umi/router";

let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

const FormItem = Form.Item;

@connect(({inquiryModel}) => ({
    inquiryModel,
}))
class InquiryDetail extends React.Component {

    state = {
        //-- 询价单id
        inquiryId: '',
        //-- 询价单数据
        inquiryData: [],
        //-- 电梯设备列表数据
        inquiryRelationData: [],
        //-- 加载层
        loading: false,
        //-- 选中的RowKeys
        selectedRowKeys: [],
        //-- 选中的Rows
        selectedRows: [],
        //-- 展示详情(不显示按钮)
        showDetail: false,
        //-- 编辑联系人模态框
        showModalContactor: false,
        //-- 编辑联系人模态框
        showModalInquiryStatus: false,
        //-- 提交询价结果模态框
        showResultModal: false,
        //-- 编辑电梯备注模态框
        showModalElevatorRemarkForm: false,
        //-- 电梯备注信息
        remarkForm: {}
    }

    componentDidMount() {
        const {state} = this.props.location;
        if (witty.isValidObj(state)) {
            const {id, showDetail} = state;
            this.setState({
                inquiryId: id,
                showDetail: showDetail
            })
            this.getInquiryRelationDataById(id);
            this.getInquiryDataById(id);
        }
    }

    /**
     * 获获取询价单信息数据
     */
    getInquiryDataById = (id) => {
        const thisCtx = this;
        const {dispatch} = this.props;

        dispatch({
            type: 'inquiryModel/getInquiryInfo',
            payload: {id},
            callback: function (data) {
                if (data && data.success) {
                    console.log(data.datas.map);
                    thisCtx.setState({
                        inquiryData: data.datas.map,
                    });
                } else {
                    message.error('询价单信息数据获取失败');
                }
            }
        });
    }

    /**
     * 获取电梯设备列表数据
     */
    getInquiryRelationDataById = (id) => {
        const thisCtx = this;
        const {dispatch} = this.props;

        let params = {}
        params.currentPage = pagingData._current;
        params.pageSize = pagingData._pageSize;
        params.inquiryId = id;

        console.log(params);
        dispatch({
            type: 'inquiryModel/inquiryRelationList',
            payload: params,
            callback: function (data) {
                if (data && data.success) {
                    console.log(data.datas.list);
                    const paging = data.datas.pagination;
                    pagingData._current = paging.current + 1;
                    pagingData._pageSize = paging.pageSize;
                    pagingData._total = paging.total;
                    thisCtx.setState({
                        //-- 重置选中的行
                        selectedRowKeys: [],
                        selectedRows: [],
                        inquiryRelationData: data.datas.list,
                    });
                } else {
                    message.error('电梯设备列表数据获取失败');
                }
            }
        });
    }

    handlerModal = (type) => {
        let flag = this.state[type];
        this.setState({
            [type]: !flag
        });
        this.props.form.resetFields();
    }

    handlerSaveContactor = () => {
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (err) {
                return;
            }
            const thisCtx = this;
            const {dispatch} = this.props;
            values.id = this.state.inquiryId;
            console.log(values);
            this.setState({loading: true});
            dispatch({
                type: 'inquiryModel/updateInquiryInfo',
                payload: values,
                callback: function (data) {
                    thisCtx.setState({loading: false});
                    if (data.success) {
                        message.success('修改联系人成功');
                        thisCtx.resetData();
                        thisCtx.getInquiryDataById(data.datas.id);
                        thisCtx.getInquiryRelationDataById(thisCtx.state.inquiryId);
                    } else {
                        message.error('修改联系人失败');
                    }
                }
            });
        });
    }

    resetData = () => {
        this.setState({
            inquiryData: [],
            inquiryRelationData: [],
            //-- 加载层
            loading: false,
            //-- 选中的RowKeys
            selectedRowKeys: [],
            //-- 选中的Rows
            selectedRows: [],
            //-- 编辑联系人
            showModalContactor: false,
            //-- 编辑联系人模态框
            showModalInquiryStatus: false
        });
        this.props.form.resetFields();
    }

    handlerPreInquiryStatus = (params) => {
        this.params = params;
        if (witty.isValidObj(params)) {
            const thisCtx = this;
            params.id = this.state.inquiryId;
            delete params.uorgName;
            this.handlerInquiryStatus(params, function (data) {
                thisCtx.setState({loading: false});
                if (data && data.success) {
                    message.success('修改询价状态成功');
                    thisCtx.resetData();
                    thisCtx.getInquiryDataById(thisCtx.state.inquiryId);
                    thisCtx.getInquiryRelationDataById(thisCtx.state.inquiryId);
                } else {
                    message.error('修改询价状态失败');
                }
            });
        }
    }

    handlerPreSubmitInquiry = () => {
        const thisCtx = this;
        let params = {};
        params.id = this.state.inquiryId;
        params.xstatus = '1';
        this.handlerInquiryStatus(params, function (data) {
            thisCtx.setState({loading: false});
            if (data && data.success) {
                message.success('询价已提交成功');
                thisCtx.resetData();
                thisCtx.handlerModal('showResultModal');
            } else {
                message.error('询价已提交失败');
            }
        });
    }

    handlerInquiryStatus = (params, callback) => {
        const {dispatch} = this.props;
        if (witty.isValidObj(params)) {
            console.log(params);
            this.setState({loading: true});
            dispatch({
                type: 'inquiryModel/inquiryAudit',
                payload: params,
                callback: callback
            });
        }
    }

    handlerElevatorRemark = (params) => {
        this.params = params;
        if (witty.isValidObj(params)) {
            const thisCtx = this;
            console.log(params);
            return;
            this.setState({loading: true});
            dispatch({
                type: 'inquiryModel/inquiryAudit',
                payload: params,
                callback: function (data) {
                    thisCtx.setState({loading: false});
                    if (data && data.success) {
                        message.success('修改备注成功');
                        thisCtx.resetData();
                        thisCtx.getInquiryDataById(thisCtx.state.inquiryId);
                        thisCtx.getInquiryRelationDataById(thisCtx.state.inquiryId);
                    } else {
                        message.error(data.msg);
                    }
                }
            });
        }
    }

    handlerDelElevator = () => {
        const {selectedRowKeys} = this.state;
        if (selectedRowKeys.length == 1) {
            const thisCtx = this;
            const {dispatch} = this.props;
            this.setState({loading: true});
            dispatch({
                type: 'inquiryModel/delInquiryRelation',
                payload: {id: selectedRowKeys[0]},
                callback: function (data) {
                    thisCtx.setState({loading: false});
                    if (data && data['success']) {
                        message.success('删除数据成功');
                        thisCtx.resetData();
                        thisCtx.getInquiryDataById(data.datas.id);
                        thisCtx.getInquiryRelationDataById(thisCtx.state.inquiryId);
                    } else {
                        message.error('删除数据失败');
                    }
                }
            })
        } else {
            message.info('请选择一行数据');
        }
    }

    handlerResult = () => {
        this.setState({
            showResultModal: false
        });
        router.push({
            pathname: '/manage/elevator'
        });
    }

    render() {

        const {showModalElevatorRemarkForm, remarkForm, showDetail, showModalContactor, showModalInquiryStatus, showResultModal, inquiryId, loading, selectedRowKeys, inquiryData, inquiryRelationData} = this.state;

        const {getFieldDecorator} = this.props.form;

        const buttonsStyle = {
            style: {
                marginRight: '15px',
            },
        };

        const formList = [
            {
                type: 'INPUT',
                label: '投保单位',
                field: 'iorgName',
                initialValue: inquiryData.iorgName,
                props: {
                    disabled: true
                }
            },
            {
                type: 'SELECT',
                label: '询价状态',
                field: 'xstatus',
                initialValue: inquiryData.xstatus,
                list: [{id: 2, name: '已报价'}]
            },
            {
                type: 'TEXT',
                label: '备注',
                field: 'remark',
                initialValue: inquiryData.remark,
                props: {
                    autoSize: {
                        minRows: 4,
                        maxRows: 4
                    }
                }
            }
        ]

        const remarkFormList = [
            {
                type: 'INPUT',
                label: '设备ID',
                field: 'id',
                initialValue: remarkForm.id,
                props: {
                    disabled: true
                }
            },
            {
                type: 'INPUT',
                label: '设备代码',
                field: 'elevatorCode',
                initialValue: remarkForm.elevatorCode,
                props: {
                    disabled: true
                }
            },
            {
                type: 'TEXT',
                label: '备注',
                field: 'remark',
                initialValue: remarkForm.remark,
                props: {
                    autoSize: {
                        minRows: 4,
                        maxRows: 4
                    }
                }
            }
        ]

        /**
         * 表格选中事件
         */
        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows,
                });
            },
        };

        const colLayout = {
            xs: 24,
            sm: 24,
            md: 24,
            lg: 8
        }

        const formLayout = {
            layout: 'horizontal',
            labelCol: {
                xs: 24,
                sm: 10
            },
            wrapperCol: {
                xs: 24,
                sm: 14
            }
        }

        const editModalFormLayout = {
            layout: 'horizontal',
            labelCol: {
                xs: 24,
                sm: 7
            },
            wrapperCol: {
                xs: 24,
                sm: 14
            }
        }

        const contactorModalFormLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 15},
            },
        }

        const xStatusData = {
            0: '待提交',
            1: '待报价',
            2: '已报价',
            3: '已过期'
        }

        const resultLayout = {
            maxWidth: '560px',
            margin: '0 auto',
            padding: '24px 0 8px'
        }

        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper>
                    <Card title={'询价信息'}>
                        <Form {...formLayout}>
                            <Row>
                                <Col {...colLayout}>
                                    <FormItem label={'报价ID'} key={'id'}>
                                        {inquiryData.id}
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'询价时间'} key={'createTime'}>
                                        {inquiryData.createTime}
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'询价状态'} key={'xstatus'}>
                                        {xStatusData[inquiryData.xstatus]}
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'投保单位'} key={'iorgName'}>
                                        {inquiryData.iorgName}
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'投保电梯数量'} key={'icount'}>
                                        {inquiryData.icount}
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={
                                        <span>报价保费
                                            <em style={{
                                                color: 'gray',
                                                fontStyle: 'normal'
                                            }}>(元)</em>
                                        </span>
                                    } key={'totalPrice'}>
                                        {inquiryData.totalPrice}
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'联系人'} key={'contactor'}>
                                        {
                                            <div>{inquiryData.contactor}</div>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'手机号码'} key={'tel'}>
                                        {
                                            <div>{inquiryData.tel}</div>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...colLayout}>
                                    <FormItem label={'邮箱'} key={'email'}>
                                        {
                                            <div>{inquiryData.email}</div>
                                        }
                                    </FormItem>
                                </Col>
                                <Col style={{marginLeft: '30px', fontSize: 18}} span={24}>
                                    <span style={{fontWeight: 900}}>备注:</span>
                                    <span style={{color: 'red'}}>{inquiryData.remark}</span>
                                </Col>
                                {
                                    showDetail ?
                                        ''
                                        :
                                        <Col span={24}
                                             style={{textAlign: 'center', height: '32px', lineHeight: '32px'}}>
                                            <FormItem wrapperCol={{xs: 24, sm: 24, md: 24, lg: 24}}>
                                                {
                                                    <span>
                                                <Button style={{marginLeft: '30px'}} type={'primary'}
                                                        onClick={() => this.handlerModal('showModalContactor')}
                                                >编辑联系人</Button>
                                                    <Button style={{marginLeft: '30px'}} type={'primary'}
                                                            onClick={() => router.push('/manage/elevator')}
                                                    >取消</Button>
                                                        {
                                                            inquiryData.xstatus == 1 ?
                                                                null
                                                                :
                                                                <Button style={{marginLeft: '30px'}} type={'primary'}
                                                                        onClick={() => this.handlerPreSubmitInquiry()}
                                                                >提交询价</Button>
                                                        }
                                                </span>
                                                }
                                            </FormItem>
                                        </Col>
                                }
                            </Row>
                        </Form>
                    </Card>

                    {
                        showDetail ?
                            ''
                            :
                            <Card style={{width: '100%', marginTop: '10px'}}>
                                <Tooltip
                                    title={selectedRowKeys.length > 0 && selectedRowKeys.length == 1 ? '' : '请选中一行数据'}>
                                    <Popconfirm
                                        title="确定删除选中的数据吗？"
                                        onConfirm={() => this.handlerDelElevator()}
                                        okText="删除"
                                        cancelText="取消"
                                        disabled={!(selectedRowKeys.length > 0 && selectedRowKeys.length == 1)}
                                    >
                                        <Button type="danger" icon="delete" {...buttonsStyle}>
                                            删除
                                        </Button>
                                    </Popconfirm>
                                </Tooltip>
                            </Card>
                    }

                    <Card style={{width: '100%', marginTop: '10px', overflow: "auto"}}>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            rowSelection={rowSelection}
                            columns={this.columns}
                            dataSource={inquiryRelationData}
                            pagination={{
                                pageSize: pagingData._pageSize,
                                current: pagingData._current,
                                total: pagingData._total,
                                onChange: (page) => {
                                    pagingData._current = page;
                                    this.getInquiryRelationDataById(inquiryId);
                                },
                                showTotal: total => `共 ${total} 条数据`,
                                style: {
                                    float: "left"
                                }
                            }}
                        />
                    </Card>
                    <Modal
                        title={'修改联系人信息'}
                        visible={showModalContactor}
                        footer={false}
                        width={500}
                        onCancel={() => this.handlerModal('showModalContactor')}
                    >
                        <Form {...contactorModalFormLayout}>
                            <FormItem label={'联系人'} key={'contactor'}>
                                {
                                    getFieldDecorator('contactor', {
                                        initialValue: inquiryData.contactor,
                                    })(
                                        <Input type={'primary'}/>
                                    )
                                }
                            </FormItem>
                            <FormItem label={'手机号码'} key={'tel'}>
                                {
                                    getFieldDecorator('tel', {
                                        initialValue: inquiryData.tel,
                                        rules: [
                                            {
                                                pattern: /^1\d{10}$/,
                                                message: '请输入正确的手机号',
                                            },
                                        ]
                                    })(
                                        <Input type={'primary'}/>
                                    )
                                }
                            </FormItem>
                            <FormItem label={'邮箱'} key={'email'}>
                                {
                                    getFieldDecorator('email', {
                                        initialValue: inquiryData.email,
                                        rules: [
                                            {
                                                type: 'email',
                                                message: '请输入正确的邮箱地址',
                                            },
                                        ]
                                    })(
                                        <Input type={'primary'}/>
                                    )
                                }
                            </FormItem>
                            <FormItem style={{textAlign: 'center'}} wrapperCol={{xs: 24, sm: 24, md: 24, lg: 24}}>
                                <Button onClick={() => this.handlerModal('showModalContactor')}>取消</Button>
                                <Button type={'primary'} style={{margin: '0 20px'}}
                                        onClick={() => this.handlerSaveContactor()}>保存</Button>
                            </FormItem>
                        </Form>
                    </Modal>
                    <Modal
                        title={'标记为已报价'}
                        visible={showModalInquiryStatus}
                        footer={false}
                        width={500}
                        onCancel={() => this.handlerModal('showModalInquiryStatus')}
                    >
                        <FilterForm formLayout={editModalFormLayout} colLayout={{span: 24}}
                                    submitName={'保存'} formList={formList}
                                    filterSubmit={this.handlerInquiryStatus}/>
                    </Modal>
                    <Modal
                        visible={showResultModal}
                        footer={false}
                        onCancel={() => this.handlerResult()}
                    >
                        <Result
                            style={{...resultLayout}}
                            status={'success'}
                            title={'您的询价已提交'}
                            subTitle={
                                <div style={{padding: 20}}>
                                    <div>小白管理员会在5个工作日内处理您的询价</div>
                                    <div>请留意注册所提供的邮件</div>
                                </div>}
                        ></Result>
                    </Modal>
                    <Modal
                        title={'添加备注'}
                        visible={showModalElevatorRemarkForm}
                        footer={false}
                        onCancel={() => this.handlerModal('showModalElevatorRemarkForm')}
                    >
                        <FilterForm formLayout={editModalFormLayout} colLayout={{span: 24}}
                                    submitName={'保存'} formList={remarkFormList}
                                    filterSubmit={this.handlerElevatorRemark}/>
                    </Modal>
                </PageHeaderWrapper>
            </Spin>
        );
    }

    /**
     * 表格列
     */
    columns = [
        {
            title: '使用单位',
            align: 'center',
            dataIndex: 'uorgName',
            key: 'uorgName',
        },
        {
            title: '使用地址',
            align: 'center',
            dataIndex: 'location',
            key: 'location',
        },
        {
            title: '统一社会信用代码',
            align: 'center',
            dataIndex: 'ocode',
            key: 'ocode',
        },
        {
            title: '设备编号/使用编号',
            align: 'center',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '设备代码',
            align: 'center',
            dataIndex: 'elevatorCode',
            key: 'elevatorCode',
        },
        {
            title: '保险期限',
            align: 'center',
            dataIndex: 'limitDate',
            key: 'limitDate',
        },
        {
            title: '保费',
            align: 'center',
            dataIndex: 'oldPrice',
            key: 'oldPrice',
        },
    ]

}

export default Form.create()(InquiryDetail);
